<?php

namespace CMS;

class App {
	private $uri;

	public function __construct($uri) {
		$this->uri = $uri;
		Db::open();
	}

	public function run($ctrl) {
		// correct namespace
		$namespace = '\APP\Ctrl\\';

		// figure out controller
		$location = is_null($ctrl) ? 'Index' : $ctrl;
		$location = class_exists($namespace . $location) ? $location : 'Error';

		// load controller
		$class = $namespace . $location;
		$controller = new $class($this->uri);

		// output application
		if(isset($controller->json)) {
			header('Content-type: application/json');
			die(json_encode($controller->json));
		} else echo $controller;
	}

	public function __destruct() {
		Db::close();
	}
}